﻿using Mes.Domain.BoundedContext;
using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace Mes.Infrastructure.Data.BoundedContext.Extensions
{
    public static class ModelBuilderExtensions
    {
        public static ModelBuilder BuildSoftDeleteEntities(this ModelBuilder modelBuilder)
        {
            var entityTypes = modelBuilder.Model.GetEntityTypes();
            foreach (var tProp in entityTypes)
            {
                var etb = modelBuilder.Entity(tProp.ClrType);
                if (typeof(ISoftDelete).IsAssignableFrom(tProp.ClrType))
                {
                    var parameter = Expression.Parameter(tProp.ClrType, "x");
                    var body = Expression.Equal(Expression.Call(typeof(EF), nameof(EF.Property), new[] { typeof(bool) },
                        parameter, Expression.Constant(nameof(ISoftDelete.IsDeleted))), Expression.Constant(false));
                    etb.HasQueryFilter(Expression.Lambda(body, parameter));
                }
            }
            return modelBuilder;
        }
    }
}
